package com.bird.web.controller.common;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import com.bird.common.constant.Constants;
import com.bird.framework.domain.Result;
import com.bird.framework.utils.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author ruoyi
 */
@RestController
public class CaptchaController {

	@Autowired
	private RedisCache redisCache;

	/**
	 * 生成验证码
	 */
	@GetMapping("/captchaImage")
	public Result getCode(HttpServletResponse response) throws IOException {
		// 生成验证码
		int w = 111, h = 36;
		LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(w, h, 4, 2);
		// 唯一标识
		String uuid = IdUtil.simpleUUID();
		String verifyKey = Constants.System.CACHE_KEY_PREFIX + Constants.System.CACHE_CAPTCHA_CODE_KEY + uuid;
		redisCache.setCacheObject(verifyKey, lineCaptcha.getCode(), Constants.System.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		lineCaptcha.write(stream);
		try {
			Result ajax = Result.ok();
			ajax.put("uuid", uuid);
			ajax.put("img", Base64.encode(stream.toByteArray()));
			return ajax;
		} catch (Exception e) {
			e.printStackTrace();
			return Result.no(e.getMessage());
		} finally {
			stream.close();
		}
	}
}
